package com.bwie.goods.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bwie.goods.config.AlipayConfig;
import com.bwie.goods.dao.GoodsDao;
import com.bwie.goods.entity.GoodsEntity;
import com.bwie.goods.feignService.MiaoshaFeignService;
import com.bwie.goods.util.IdWorker;
import com.bwie.goods.vo.ActivityVo;
import com.bwie.goods.vo.GoodsVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.bwie.goods.entity.OrderInfoEntity;
import com.bwie.goods.service.OrderInfoService;
import com.bwie.miaosha.common.utils.PageUtils;
import com.bwie.miaosha.common.utils.R;

import javax.servlet.http.HttpServletRequest;


/**
 * 
 *
 * @author HouDing
 * @email 1398853436@qq.com
 * @date 2022-02-22 19:41:40
 */
@Controller
@RequestMapping("goods/orderinfo")
@SuppressWarnings("all")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private GoodsDao goodsDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private MiaoshaFeignService miaoshaFeignService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = orderInfoService.queryPage(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/pay")
    @ResponseBody
    public R alipay(@RequestParam("id") Long id) throws Exception {
        OrderInfoEntity orderInfoEntity = orderInfoService.findOrderById(id);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = new String(orderInfoEntity.getOrderno().toString().getBytes(), "UTF-8");
        System.out.println(orderInfoEntity.getId());
        //付款金额，必填
        String total_amount = new String(orderInfoEntity.getMiaoshaPrice().toString().getBytes(), "UTF-8");
        //订单名称，必填
        String subject = new String(orderInfoEntity.getGoodsName().getBytes(), "UTF-8");
        //商品描述，可空
        String body = new String("美国有苹果，中国有菠萝。菠萝手机，外置18亿高清摄像".getBytes(), "UTF-8");
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
        System.out.println(alipayRequest);
        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        //输出
        return R.ok().put("connect",result);
    }
    //支付回调
    @RequestMapping("/success")
    public String paysuccess(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
//
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
//
//        //——请在这里编写您的程序（以下代码仅作参考）——
//        if(signVerified) {
        //商户订单号
        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
//        QueryWrapper<OrderInfoEntity> wrapper = new QueryWrapper<OrderInfoEntity>().eq("order_id", out_trade_no);
//        OrderInfoEntity orderInfoEntity = orderInfoService.getOne(wrapper);
//        orderInfoEntity.setPayDate(new Date());
//        orderInfoEntity.setStatus(1);
//        orderInfoService.updateById(orderInfoEntity);
        //支付宝交易号
        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //付款金额
        String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

        System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);

        OrderInfoEntity order = orderInfoService.findOrderByOrderno((out_trade_no));
        if (order!=null){
            if (order.getMiaoshaPrice().toString().equals(total_amount) ){
                order.setStatus(1);
                order.setPayDate(new Date());
                orderInfoService.updateById(order);
                return "redirect:http://192.168.244.197/miaosha/orderlist.html";
            }
            return "redirect:http://192.168.244.197/miaosha/orderlist.html";
        }
        return "redirect:http://192.168.244.197/orderlist.html";
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @ResponseBody
    public R info(@PathVariable("id") Long id){
		OrderInfoEntity orderInfo = orderInfoService.findOrderById(id);

        return R.ok().put("orderInfo", orderInfo);
    }
    //添加订单
    @RequestMapping("/addOrder/{uid}")
    @ResponseBody
    public R addOrder(@RequestBody OrderInfoEntity orderInfoEntity,@PathVariable("uid") Long uid) throws Exception{
        RLock mylock = redissonClient.getLock("mylock");
        try{
            boolean b = mylock.tryLock(30, 10, TimeUnit.SECONDS);
            if (b) {
                ActivityVo activityVo = orderInfoService.findOrderByGoodId(orderInfoEntity.getGoodsId());
                if (activityVo.getStockCount() == null || activityVo.getStockCount() == 0) {
                    return R.error("抱歉，库存不足！");
                }
                //添加订单表
                OrderInfoEntity order = orderInfoService.check(orderInfoEntity.getUserId(),orderInfoEntity.getGoodsId());
                if (order!=null) {
                    return R.error("用户已经购买过，请勿重复购买！");
                }
                //秒杀商品表的商品库存减1
                /*String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");*/
                orderInfoEntity.setOrderno(String.valueOf(idWorker.nextId()));
                orderInfoEntity.setCreateDate(new Date());
                orderInfoEntity.setStatus(0);
                orderInfoEntity.setUserId(uid);
                orderInfoService.save(orderInfoEntity);
                GoodsEntity goodsEntity = goodsDao.selectById(orderInfoEntity.getGoodsId());
                goodsEntity.setGoodsStock(goodsEntity.getGoodsStock()-orderInfoEntity.getGoodsCount());
                goodsDao.updateById(goodsEntity);
                return R.ok();
            }
        }finally {
            //解锁
            mylock.unlock();
        }
        return R.error();
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @ResponseBody
    public R save(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.save(orderInfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @ResponseBody
    public R update(@RequestBody OrderInfoEntity orderInfo){
		orderInfoService.updateById(orderInfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody Long[] ids){
		orderInfoService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
